package com.auto.autoapp.ui.activity

import android.content.Intent
import android.graphics.Rect
import android.view.View
import android.widget.EditText
import android.widget.Toast
import com.auto.autoapp.base.BaseActivity
import com.auto.autoapp.databinding.ActivityCommentPrivateMessageBinding
import com.auto.autoapp.model.CommentPrivateMessageSetting
import com.auto.autoapp.services.FloatingWindowService
import com.auto.autoapp.task.CommentPrivateMsgTask
import com.auto.autoapp.util.SpUtil
import com.auto.autoapp.widgets.SettingItemView
import com.auto.autoapp.widgets.SimpleToolbar
import com.ven.assists.stepper.StepManager
import kotlin.math.max


/**
 * 搜索视频评论区意向客户私信
 * 搜索关键字查找到相关视频，对视频评论区意向客户进行私信
 */
class CommentPrivateMessageActivity : BaseActivity() {
    private lateinit var binding: ActivityCommentPrivateMessageBinding
    override fun provideView(): View {
        binding = ActivityCommentPrivateMessageBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun configToolbar(toolbar: SimpleToolbar) {
        super.configToolbar(toolbar)
        toolbar.setTitle(intent.getStringExtra("title"))
    }

    override fun onInit() {
        // 读取并展示已保存配置（聚合对象）
        val pm = SpUtil.getCommentPrivateMsgSetting()
        binding.sivSearchKeywords.setValues(listOf(pm.searchKeywords))
        binding.sivVideoSeconds.setValues(listOf(pm.videoSeconds.toString()))
        binding.sivLikeProbability.setValues(listOf(pm.likeProbability.toString()))
        binding.sivCommentInclude.setValues(listOf(pm.commentIncludeKeywords))
        binding.sivCommentExclude.setValues(listOf(pm.commentExcludeKeywords))
        binding.sivFollowProbability.setValues(listOf(pm.followProbability.toString()))
        binding.sivDmProbability.setValues(listOf(pm.dmProbability.toString()))
        binding.sivMaxCommentCount.setValues(listOf(pm.maxCommentCount.toString()))
        binding.sivDmMessages.setValues(pm.dmMessages)

        // 焦点滚动适配
        attachFocusScroll(binding.sivSearchKeywords)
        attachFocusScroll(binding.sivVideoSeconds)
        attachFocusScroll(binding.sivLikeProbability)
        attachFocusScroll(binding.sivCommentInclude)
        attachFocusScroll(binding.sivCommentExclude)
        attachFocusScroll(binding.sivFollowProbability)
        attachFocusScroll(binding.sivDmProbability)
        attachFocusScroll(binding.sivDmMessages)

        binding.btnConfirm.setOnClickListener {
            // 取值并校验
            val kw = binding.sivSearchKeywords.getValues().firstOrNull()?.trim().orEmpty()
            val videoStr = binding.sivVideoSeconds.getValues().firstOrNull()?.trim().orEmpty()
            val likeStr = binding.sivLikeProbability.getValues().firstOrNull()?.trim().orEmpty()
            val includeKw = binding.sivCommentInclude.getValues().firstOrNull()?.trim().orEmpty()
            val excludeKw = binding.sivCommentExclude.getValues().firstOrNull()?.trim().orEmpty()
            val followStr = binding.sivFollowProbability.getValues().firstOrNull()?.trim().orEmpty()
            val dmStr = binding.sivDmProbability.getValues().firstOrNull()?.trim().orEmpty()
            val maxCommentStr =
                binding.sivMaxCommentCount.getValues().firstOrNull()?.trim().orEmpty()
            val dmList =
                binding.sivDmMessages.getValues().map { it.trim() }.filter { it.isNotEmpty() }

            // 清除旧错误
            fun clearError(item: SettingItemView) {
                item.findViewById<EditText>(com.auto.autoapp.R.id.et_value)?.error = null
            }
            clearError(binding.sivSearchKeywords)
            clearError(binding.sivVideoSeconds)
            clearError(binding.sivLikeProbability)
            clearError(binding.sivCommentInclude)
            clearError(binding.sivCommentExclude)
            clearError(binding.sivFollowProbability)
            clearError(binding.sivDmProbability)
            // 列表第一个输入框用作错误提示
            binding.sivDmMessages.findViewById<EditText>(com.auto.autoapp.R.id.et_value)?.error =
                null

            var hasError = false

            if (kw.isBlank()) {
                binding.sivSearchKeywords.findViewById<EditText>(com.auto.autoapp.R.id.et_value)?.error =
                    "请输入关键字"
                hasError = true
            }

            val videoSeconds = videoStr.toIntOrNull()
            if (videoSeconds == null || videoSeconds <= 0) {
                binding.sivVideoSeconds.findViewById<EditText>(com.auto.autoapp.R.id.et_value)?.error =
                    "请输入大于0的整数秒数"
                hasError = true
            }

            val likePercent = likeStr.toIntOrNull()
            if (likePercent == null || likePercent !in 0..100) {
                binding.sivLikeProbability.findViewById<EditText>(com.auto.autoapp.R.id.et_value)?.error =
                    "请输入 0-100 的整数"
                hasError = true
            }

            val followPercent = followStr.toIntOrNull()
            if (followPercent == null || followPercent !in 0..100) {
                binding.sivFollowProbability.findViewById<EditText>(com.auto.autoapp.R.id.et_value)?.error =
                    "请输入 0-100 的整数"
                hasError = true
            }

            val dmPercent = dmStr.toIntOrNull()
            if (dmPercent == null || dmPercent !in 0..100) {
                binding.sivDmProbability.findViewById<EditText>(com.auto.autoapp.R.id.et_value)?.error =
                    "请输入 0-100 的整数"
                hasError = true
            }

            if ((dmPercent ?: 0) > 0 && dmList.isEmpty()) {
                binding.sivDmMessages.findViewById<EditText>(com.auto.autoapp.R.id.et_value)?.error =
                    "请输入至少一条私信文字"
                hasError = true
            }
            val maxCommentCount = maxCommentStr.toIntOrNull()

            if (hasError) {
                Toast.makeText(this, "请修正标红项后再确认", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            // 保存到本地（聚合对象）
            SpUtil.setCommentPrivateMsgSetting(
                CommentPrivateMessageSetting(
                    searchKeywords = kw,
                    videoSeconds = videoSeconds!!,
                    likeProbability = likePercent!!,
                    commentIncludeKeywords = includeKw,
                    commentExcludeKeywords = excludeKw,
                    followProbability = followPercent!!,
                    dmProbability = dmPercent!!,
                    dmMessages = dmList,
                    maxCommentCount = maxCommentCount ?: 10
                )
            )
            if (FloatingWindowService.getInstance() == null) {
                val intent = Intent(this, FloatingWindowService::class.java)
                intent.action = "SHOW_FLOATING_WINDOW"
                startService(intent)
            }

            StepManager.isStop = true
            StepManager.execute(CommentPrivateMsgTask::class.java, 1, begin = true)
        }
    }

    private fun attachFocusScroll(item: SettingItemView) {
        item.setOnChildFocusListener { target ->
            scrollToView(target)
        }
    }

    private fun scrollToView(target: View) {
        binding.scrollContent.post {
            val rect = Rect()
            target.getDrawingRect(rect)
            binding.scrollContent.offsetDescendantRectToMyCoords(target, rect)
            val y = (rect.top - dp(24)).coerceAtLeast(0)
            binding.scrollContent.smoothScrollTo(0, y)
        }
    }

    private fun dp(value: Int): Int {
        val d = resources.displayMetrics.density
        return (value * d).toInt()
    }
}